from instance.app_instance import app

from flask_principal import identity_loaded, Identity, UserNeed, RoleNeed
from flask_login import current_user

from models.user_model import UserModel
from permissions.role_permission import *
from permissions.project_permission import *

@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    assert isinstance(identity, Identity)
    assert isinstance(current_user, UserModel)

    # Set the identity user object
    identity.user = current_user

    identity.provides.add(UserNeed(current_user.get_id()))

    for role in current_user.get_roles():
        identity.provides.add(RoleNeed(role))

    for project in current_user.get_projects():
        identity.provides.add(ProjectReadNeed(unicode(project)))
        identity.provides.add(ProjectEditNeed(unicode(project)))
